<?php

namespace app\api\controller;

use think\Db;
use app\api\model\VolleyDesc as Balance;
use app\api\model\YaoqingRecords;
use app\api\model\UserDeedLimit;
use app\api\model\UserClaimAddress;

class Experience extends Common
{
    public function PrePublish()
    {
        $pre = [
            1=>['price'=>[0,10],'name'=>'专业'],
            2=>['price'=>[0,10], 'name'=>'经验']
        ];
        return $this->pass($pre);
    }

    public function publish() {
        $checkDymanic = Db::name('config_system')->where(['title' => 'check_dymanic_exp'])->value('content');

        $data       = input('post.');
        $data['class'] = $data['class'] ?? 2;
        if ($data['class'] != 2) {
            return $this->miss('类别错误');
        }
        $topic = $data['topic'] ?? '';
        $topic_experience = $data['topic_experience'] ?? '';

        $address_id = $data['address_id'] ?? '';
        $address = $data['address'] ?? '';
        $address_desc = $data['address_desc'] ?? '';
        $longitude = $data['longitude'] ?? '';
        $latitude = $data['latitude'] ?? '';
        $citys = $data['citys'] ?? '';

        $insertKeys = ['category_id', 'title', 'content', 'masterimg', 'video', 'cover', 'community_id', 'class', 'price', 'topic', 'address', 'address_id', 'citys', 'longitude', 'latitude', 'private'];
        foreach ($data as $key => $item) {
            if (!in_array($key, $insertKeys)) {
                unset($data[$key]);
                continue;
            }
            $data[$key] = strip_tags($item);
        }
        $data['userid'] = $this->member['id'];

        // if (!$data['title']) {
        //     return $this->miss('请输入标题');
        // }
        if (!$data['content']) {
            return $this->miss('请输入内容');
        }

        $limit = UserDeedLimit::check($this->member['id'], 1);
        if ($limit) {
            return $this->miss('当前已被限制发布内容');
        }
        
        if (isset($data['category_id']) && $data['category_id']) {
            $cate = Db::name('labels')->where(['id' => ['in', $data['category_id']], 'parent_id' => ['<>', 0], 'is_hidden' => 0])->field('id,name')->select();
            if (!$cate) {
                return $this->miss('分类不存在');
            }
        }


        $contain = Db::name('filter_word')->where(['state' => 1])->column('name');
        foreach ($contain as $k => $v) {
            if (stripos($data['title'], $v) !== false) {
                return $this->miss('标题含有敏感词"' . $v . '",请重新编辑发送');
            }
            if (stripos($data['content'], $v) !== false) {
                return $this->miss('内容含有敏感词"' . $v . '",请重新编辑发送');
            }
            if (stripos($topic, $v) !== false) {
                return $this->miss('标签含有敏感词"' . $v . '",请重新编辑发送');
            }
        }

        if ($topic) {
            $topic = array_filter(explode('#', $topic));
            $topics = Db::name('topic')->where(['name'=>['in', $topic]])->column('id', 'name');
            $topics_name = array_keys($topics);
            foreach ($topic as $key => $value) {
                if (!$value) continue;
                if (in_array($value, $topics_name)) {
                    Db::name('topic')->where(['id'=>$topics[$value]])->setInc('count');
                } else {
                    Db::name('topic')->insert(['name'=>$value,'count'=>1,'user_id'=>$this->member['id'], 'create_time'=>time()]);
                }
            }
        }

        $data['topic_experience'] = [];
        if ($topic_experience) {
            $topic_experience = array_filter(explode('#', $topic_experience));
            $topics = Db::name('topic')->where(['name'=>['in', $topic_experience]])->field('id,name')->select();
            $topics_name = array_keys($topics);
            foreach ($topics as $key => $value) {
                $hasTopicExp = Db::name('user_attestation')->where('find_in_set('.$value['id'].', category)')->where(['user_id'=>$this->member['id'], 'status'=>1])->find();
                if ($hasTopicExp) {
                    $data['topic_experience'][] = $value['name'];
                }
            }

            if ($data['topic_experience']) {
                $data['topic_experience'] = '&'.implode(' &', $data['topic_experience']);
            } else {
                return $this->miss('所选经验未认证');
            }
        } else {
            $data['price'] = 0;
        }

        $data['price'] = isset($data['price']) ? $data['price'] : 0;
        if ($data['price'] < 0 || $data['price'] > 10) {
            return $this->miss('经验付费阅读价格应在:0~10元');
        }

        if ($address) {
            if (!$address_id) {
                $data['address_id'] = UserClaimAddress::FindByCreate(['name' => $address, 'address' => $address_desc, 'longitude' => $longitude, 'latitude' => $latitude, 'city' => $citys]);
            }
        }

        if ($checkDymanic + 0) {
            $data['shenhe'] = $checkDymanic ? 0 : 1;
            $msg            = '发布成功，待审核通过';
        } else {
            $msg = '发布成功';

            Db::name('user')->where(['id' => $this->member['id']])->setInc('charm_value', 10);
        }

        $masterimg = $data['masterimg'] ?? '';

        if ($masterimg) {
            $masterimg = explode(',', $masterimg);
            $sumbImage = '';
            foreach ($masterimg as $k => $v) {
                $thumb_    = explode('.', $v);
                $thumb1    = $thumb_[0] . '_thumb.' . $thumb_[1];
                $sumbImage = $sumbImage ? $sumbImage . ',' . $thumb1 : $thumb1;
            }
            $data['sumbImage'] = $sumbImage;
        }
        $data['thumbsup'] = 0;
        $data['visit'] = 1;
        $data['enroll'] = 0;

        $videoOssSwitch = getenv('APP_OSS_VIDEO_UPLOAD');
        if (!$videoOssSwitch) {
            $data['enroll'] = 1;
        }
        
        $data['liveness'] = _calculateHotScoreNew(1, 0, 0, 0, datetime());

        $insetId = Db::name('dymanic')->insertGetId($data);

        if ($insetId) {
            if (isset($data['video']) && $data['video'] && $data['enroll']) {
                _rabbitMqPublish('ffmpeg', [
                    'id' => $insetId
                ]);
            }
            return $this->pass($msg);
        }
        return $this->miss('发布失败', 201);
    }


    public function subscribe($dy_id)
    {
        $article = Db::name('dymanic')->where(['dy_id'=>$dy_id, 'shenhe'=>1, 'class'=>2])->find();
        if (!$article) {
            return $this->pass('内容飞走了');
        }
        if ($article['userid'] == $this->member['id']){
            return $this->pass('错误操作');
        }

        $paystate = Db::name('order_of_subscribe')->where(['user_id'=>$this->member['id'], 'dy_id'=>$dy_id])->count();
        if ($paystate) {
            return $this->pass('已支付');
        }
        $timenow = time();
        // 支付
        $total = getenv('APP_RATE') * $article['price'];
        // 兑换成收款方对应汇率积分
        $toScore = $total;
        $rate = Db::name('config_system')->where(['title'=>'fencheng_user'])->value('content');
        $content = '订阅文章';
        $number = uniqid('sub');
        $orders = [
            'user_id' => $this->member['id'],
            'touserid' => $article['userid'],
            'order_sn'  => $number,
            'totalprice' => $toScore,
            'rate' => $rate,
            'price' => $toScore * $rate,
            'dy_id' => $article['dy_id'],
            'dy_title' => $article['title'],
            'time' => $timenow
        ];

        if ($this->member['volley'] < $total) {
            return $this->miss('账户余额不足', 507);
        }

        $touser = Db::name('user')->where(['id'=>$article['userid']])->field('id,score')->find();

        // 启动事务
        Db::startTrans();
        try {
            $BalanceState = Balance::index($this->member['id'], $total, $content . ' no.' . $number);

            $insert = Db::name('order_of_subscribe')->insertGetId($orders);
            $orders['id'] = $insert;

            $IncomeState = YaoqingRecords::index($article['userid'], $this->member['id'], $orders['price'], '经验文章 「'.$article['title'].'」 收益', 1, $insert);

            $orders['toScore'] = $toScore;
            Db::name('order_common')->insert([
                'types' => 8,
                'number'=> $number,
                'user_id'=>$this->member['id'],
                'money' => $total,
                'data'  => json_encode($orders, JSON_UNESCAPED_UNICODE),
                'pays'  => 1,
                'status'=> 1,
                'create_time'=>$timenow,
                'update_time'=>$timenow
            ]);

            if($BalanceState && $IncomeState && $insert){
                // 提交事务
                Db::commit();
            }else{
                throw new \think\Exception('订阅文章异常，请重试', 100010);
            }
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();

            return $this->miss($e->getMessage());
        }

        return $this->pass('支付成功');
    }
}